﻿<template>
  <a-card :title="modifyEntity.title">

    <!--表单-->
    <a-spin :spinning="spinning">
      <a-form-model ref="modelForm" :model="model" :rules="rules" :labelCol="labelCol" :wrapperCol="wrapperCol">

        <a-row>
          <a-col :lg="12" :md="12" :sm="12">
            <a-form-model-item label="项目类型" required prop="projectType">
              <a-select allowClear v-model="model.projectType" placeholder="请选择项目类型" style="width: 100%">
                <a-select-option v-for="item in projectTypeList" :key="item" :value="item">{{ item }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :lg="12" :md="12" :sm="12">
            <a-form-model-item label="项目类别" required prop="category">
              <a-select allowClear v-model="model.category" placeholder="请选择项目类别" style="width: 100%">
                <a-select-option v-for="item in categoryList" :key="item" :value="item">{{ item }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :lg="12" :md="12" :sm="12">
            <a-form-model-item label="项目名称" required prop="name">
              <a-input v-model="model.name" placeholder="请输入项目名称" />
            </a-form-model-item>
          </a-col>
          <a-col :lg="12" :md="12" :sm="12">
            <a-form-model-item label="标记">
              <a-input v-model="model.flag" placeholder="请输入标记" />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :lg="12" :md="12" :sm="12">
            <a-form-model-item label="体验价格" required prop="experiencePrice">
              <a-input-number v-model="model.experiencePrice" placeholder="请输入体验价格" style="width: 100%" :step="0.001" :precision="5" />
            </a-form-model-item>
          </a-col>
          <a-col :lg="12" :md="12" :sm="12">
            <a-form-model-item label="单次价格" required prop="singlePrice">
              <a-input-number v-model="model.singlePrice" placeholder="请输入单次价格" style="width: 100%" :step="0.001" :precision="5" />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :lg="12" :md="12" :sm="12">
            <a-form-model-item label="月卡价格" required prop="monthlyCardPrice">
              <a-input-number v-model="model.monthlyCardPrice" placeholder="请输入月卡价格" style="width: 100%" :step="0.001" :precision="5" />
            </a-form-model-item>
          </a-col>
          <a-col :lg="12" :md="12" :sm="12">
            <a-form-model-item label="状态" required>
              <a-switch v-model="model.status" un-checked-children="否" checked-children="是" />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row v-if="model.projectType == '智能体'">
          <a-col :lg="12" :md="12" :sm="12">
            <a-form-model-item label="智能体ID" required prop="botId">
              <a-input v-model="model.botId" placeholder="请输入智能体ID" />
            </a-form-model-item>
          </a-col>
          <a-col :lg="12" :md="12" :sm="12">
            <a-form-model-item label="认证方式" required prop="method">
              <a-select allowClear v-model="model.method" placeholder="请选择认证方式" style="width: 100%">
                <a-select-option v-for="item in methodList" :key="item" :value="item">{{ item }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row v-if="model.projectType == '智能体'">
          <a-col :lg="12" :md="12" :sm="12" v-if="model.method == 'Oauth应用'">
            <a-form-model-item label="公钥" required prop="publickKey">
              <a-input v-model="model.publickKey" placeholder="请输入公钥" />
            </a-form-model-item>
          </a-col>
          <a-col :lg="12" :md="12" :sm="12" v-if="model.method == 'Oauth应用'">
            <a-form-model-item label="私钥" required prop="fileList">
              <file-upload :fileList="model.fileList" acceptTypes=".txt" @uploadCallBack="fileUploadCallBack" />
            </a-form-model-item>
          </a-col>
          <a-col :lg="12" :md="12" :sm="12" v-if="model.method == '个人访问令牌'">
            <a-form-model-item label="访问令牌" required prop="token">
              <a-input v-model="model.token" placeholder="请输入个人访问令牌" />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row v-if="model.projectType == '工作流'">
          <a-col :lg="12" :md="12" :sm="12">
            <a-form-model-item label="预设指令" required prop="instruction">
              <a-textarea v-model="model.instruction" placeholder="请输入预设指令" :rows="4" />
            </a-form-model-item>
          </a-col>
          <a-col :lg="12" :md="12" :sm="12">
            <a-form-model-item label="示例内容" required prop="example">
              <a-textarea v-model="model.example" placeholder="请输入示例内容" :rows="4" />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :lg="12" :md="12" :sm="12">
            <a-form-model-item label="图片" required prop="imgList">
              <img-upload :fileList="model.imgList" @uploadCallBack="imgUploadCallBack" />
            </a-form-model-item>
          </a-col>

          <a-col :lg="12" :md="12" :sm="12">
            <a-form-model-item label="描述">
              <a-textarea v-model="model.description" placeholder="请输入描述" :rows="4" />
            </a-form-model-item>
          </a-col>
        </a-row>

      </a-form-model>
    </a-spin>

    <!--底部按钮-->
    <footer-tool-bar>
      <a-button icon="reload" @click="handleRefresh">取消</a-button>
      <a-divider type="vertical" />
      <a-button icon="check-circle" :loading="loading" @click="handleSubmit">保存</a-button>
    </footer-tool-bar>
  </a-card>
</template>

<script>
import footerToolBar from "@/components/footerToolbar";
import imgUpload from "_c/imgUpload";
import fileUpload from "_c/fileUpload";
import { getProject, addProject, updateProject } from "./project";
import { queryDicSelect } from "@/views/sysModule/system/dic/dic";
export default {
  components: { imgUpload, fileUpload, footerToolBar },
  props: {
    modifyEntity: {
      type: Object,
      required: true,
      default: function () {
        return {
          // 传递的主键
          id: "",
          // 页面操作类型
          operation: this.operationFlag.Add,
          // 是否展示编辑页面
          showModify: false,
          // 标题
          title: "",
        };
      },
    },
  },
  data() {
    return {
      // 显示描述宽度
      labelCol: { md: { span: 4 }, xs: { span: 24 }, sm: { span: 12 } },
      // 输入框宽度
      wrapperCol: { md: { span: 18 }, xs: { span: 24 }, sm: { span: 12 } },
      // 执行保存后是否关闭当前页面
      hasClose: false,
      // 遮罩层加载
      spinning: false,
      // 按钮加载状态
      loading: false,
      // 是否只读
      readonly: false,
      model: {
        // 图片上传
        imgList: [],
        // 文件上传
        fileList: [],
      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 3, max: 30, message: '名称长度为3~30个字符之间', trigger: 'blur' },
        ],
        projectType: [
          {
            required: true,
            message: '请选择项目类型',
            trigger: 'change',
          },
        ],
        category: [
          {
            required: true,
            message: '请选择项目类别',
            trigger: 'change',
          },
        ],
        experiencePrice: [
          { required: true, message: '请输入体验价格', trigger: 'blur' },
        ],
        monthlyCardPrice: [
          { required: true, message: '请输入月卡价格', trigger: 'blur' },
        ],
        singlePrice: [
          { required: true, message: '请输入单次价格', trigger: 'blur' },
        ],
        botId: [
          { required: true, message: '请输入智能体ID', trigger: 'blur' },
        ],
        method: [
          {
            required: true,
            message: '请选择认证方式',
            trigger: 'change',
          },
        ],
        publickKey: [
          { required: true, message: '请输入公钥', trigger: 'blur' },
        ],
        imgList: [
          {
            validator: (rule, value, callback) => {
              if (!value || value.length === 0) {
                callback(new Error('请上传图标'));
              } else if (!value.every(item => item.status === 'done')) {
                callback(new Error('有文件未上传完成'));
              } else {
                callback();
              }
            },
            trigger: 'change',
          },
        ],
        fileList: [
          {
            type: 'array',
            required: true,
            message: '请上传私钥',
            trigger: 'change',
          },
        ],
        token: [
          { required: true, message: '请输入个人访问令牌', trigger: 'blur' },
        ],
        instruction: [
          { required: true, message: '请输入预设指令', trigger: 'blur' },
        ],
        example: [
          { required: true, message: '请输入示例内容', trigger: 'blur' },
        ]
      },
      // 项目类别
      categoryList: [],
      // 项目类型
      projectTypeList: ['智能体', '工作流'],
      //认证方式
      methodList: ['个人访问令牌', 'Oauth应用']
    };
  },
  created() {
    queryDicSelect({ 'dicTypeUniqueCode': 'ProjectCategory' }).then(res => {
      this.categoryList = res.data.map(item => item.name)
    });
  },
  mounted() {
    this.loadData();
  },
  methods: {
    // 文件上传回调
    fileUploadCallBack(rawFiles) {
      this.model.fileList = rawFiles.base64Content;
      this.$nextTick(() => {
        this.$refs.modelForm.validateField('fileList');
      });
    },

    // 图片上传回调
    imgUploadCallBack(rawFiles) {
      debugger
      // 转换文件为可验证的格式
      this.model.imgList = rawFiles.map(file => ({
        uid: file.uid || `file-${Date.now()}`,
        name: file.name,
        status: 'done',
        url: file.url || (file instanceof File ? URL.createObjectURL(file) : ''),
        thumbUrl: file.thumbUrl || (file instanceof File ? URL.createObjectURL(file) : ''),
        originFileObj: file
      }));

      this.$nextTick(() => {
        this.$refs.modelForm.validateField('imgList');
      });
    },
    //#region 加载数据

    loadData() {
      //修改，详情获取详细信息
      if (this.modifyEntity.operation !== this.operationFlag.Add) {
        this.spinning = true;
        // 编辑状态是只读
        this.readonly = true;
        let that = this;
        getProject(this.modifyEntity.id)
          .then((res) => {
            if (res.code != 200) {
              this.$notification.warning({ description: "数据不存在" });
              this.$emit("handleRefresh");
              return false;
            }
            that.model = res.data;
            if (that.model.icon) {
              that.model.imgList = [
                {
                  uid: "-1",
                  name: "image01.png",
                  status: "done",
                  url: that.model.icon,
                  thumbUrl: that.model.icon,
                },
              ];
            }

            if (that.model.privateKey) {
              that.model.fileList = [{
                uid: "-1",
                status: "done",
                url: that.model.privateKey,
                base64Content: that.model.privateKey // 确保包含Base64内容
              }];
            }
            that.spinning = false;
          })
          .catch((error) => {
            that.spinning = false;
          });
      }
    },
    //#endregion

    //#region 保存
    // 保存
    handleSubmit() {
      let that = this;
      this.spinning = true;
      this.loading = true;
      this.$refs.modelForm.validate(valid => {
        if (valid) {
          if (that.modifyEntity.operation === that.operationFlag.Add) {
            debugger
            if (that.model.imgList) { 
              that.model.icon = that.model.imgList[0]?.thumbUrl;
            }
            if (that.model.fileList) {
              that.model.privateKey = that.model.fileList[0]?.base64Content; // 使用Base64
            }

            addProject(that.model)
              .then((res) => {
                that.submitResult(res);
              })
              .catch((error) => {
                that.spinning = false;
                this.loading = false;
              });
          } else {
            if (that.model.imgList) {
              that.model.icon = that.model.imgList[0]?.thumbUrl;
            }
            if (that.model.fileList) {
              that.model.privateKey = that.model.fileList[0]?.base64Content; // 使用Base64
            }
            updateProject(that.model)
              .then((res) => {
                that.submitResult(res);
              })
              .catch((error) => {
                that.spinning = false;
                this.loading = false;
              });
          }
        } else {
          this.spinning = false;
          this.loading = false;
        }
      });
    },
    // 保存结果
    submitResult(res) {
      if (res.code == 200) {
        this.$notification.success({ description: res.msg });
        if (!this.hasClose) {
          this.$emit("handleRefresh");
        }
      } else {
        this.$notification.error({ description: res.msg });
      }
      this.spinning = false;
    },
    //#endregion

    //#region  取消、关闭、重置
    // 取消、关闭
    handleRefresh() {
      this.spinning = false;
      this.$emit("handleRefresh");
    },
    // 重置
    handleReset() {
      this.loadData();
    },
    //#endregion
  },
};
</script>
